/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
/* api */
import * as SettingTaskApi from '@src/api/SettingTaskApi';
/* util */
import * as FormUtil from '@src/component/form/util';
import { parse } from '@src/util/querystring'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();
export default {
  name: 'task_card_setting',
  mixins: [fieldMixin, FormDesignMixin],
  data() {
    return {
      formFieldMax: 300,
      init: false,
      loading: true,
      pending:false,
      cloneName:'',
      cardName:'',
      mode: 'task_card',
      taskCardId:'',
      fields:[],
      nameLanguage:{},
      descriptionLanguage:{},
    }
  },
  mounted(){
    let query = parse(window.location.search) || {};
    this.taskCardId = query.cardId;

    this.getTaskCardNameReq();
    this.initFieldsData();
  },
  computed:{
    // 是否允许切换语言包 老版本不限制，新版本只有国际化账号才允许切换语言包
    isShow() {
      return internationalGray;
    }
  },
  methods: {
    // 初始化表单字段
    async initFieldsData() {
      try {
        // 获取表单字段列表
        let fields = await SettingTaskApi.getAddCardFields({ cardId: this.taskCardId, isFromSetting: true });
        let sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
        
        this.fields = FormUtil.toFormField(sortedFields);
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    // 返回
    back(){
      let id = window.frameElement.dataset.id
      this.$platform.closeTab(id)

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskCardManage,
        reload: false,
      })
    },
    /** 
    * @description 提交表单字段设置
    */
    async submit() {
      try {
        if(this.cardName !== this.cloneName ){
          const params = {
            id: this.taskCardId, 
            name: this.cardName,
            titleLanguage: this.nameLanguage,
            descLanguage: this.descriptionLanguage
          }
          let res = await SettingTaskApi.updateTaskCardName(params);
          if(res.status !== 0){
            return this.$message.warning(res.message);
          }
        }
        let fields = FormUtil.toField(this.fields);
        fields.forEach((field, index) => {
          field.cardId = this.taskCardId;
          field.orderId = index;    
        });

        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;
        let result = await SettingTaskApi.taskCardFieldsSave(fields);

        let isSuccess = result.status == 0;
        this.$platform.notification({
          type: isSuccess ? 'success' : 'error',
          title: i18n.t('task.tip.taskAdditionalTip4', {state: isSuccess ? i18n.t('common.base.success') : i18n.t('common.base.fail')}),
          message: isSuccess ? null : result.message
        })
        if(isSuccess){
          setTimeout(()=>{
            this.back();
          }, 500)
        }
      } catch (error) {
        console.error(error)
      }

      this.pending = false;
    },
    
    // 获取组件名称
    getTaskCardNameReq() {
      SettingTaskApi.getTaskCardName({id: this.taskCardId}).then(res=>{
        const { status, message, data } = res;
        if(status == 0){
          this.cloneName = data.name;
          this.cardName = data.name;
          this.nameLanguage = data?.titleLanguage || {};
          this.descriptionLanguage = data?.descLanguage || {};
        }
      }).catch(error=>{
        console.log(error)
      })
    },

    // 更新组件名称
    updateTaskCardName() {
      const params = {
        id: this.taskCardId, 
        name: this.cardName,
        titleLanguage: this.nameLanguage,
        descLanguage: this.descriptionLanguage
      }
      SettingTaskApi.updateTaskCardName(params).then(res=>{
        const { status, message, data } = res;
        if(status != 0){
          this.$message.error(message);
        }
      }).catch(error=>({}))
    },

    save(form) {
      this.nameLanguage = form;
      this.cardName = form[i18n.locale];
    }
  }
}